/**
 * 路由配置文件（方案 C：核心页面预加载 + 其他页面懒加载）
 *
 * @file frontend/src/routes/index-hybrid.tsx
 * @description 折中方案：只让若干关键页面首屏秒开，其它页面继续按需加载
 *
 * 特点：
 * 1. 核心页面：直接导入组件，不使用 React.lazy，首次点击也不会出现加载等待
 * 2. 其它页面：保持懒加载，减小首屏体积
 * 3. 保持类型安全和 IDE 跳转
 */

import React, { lazy, Suspense, ComponentType } from 'react';
import { RouteObject, Navigate } from 'react-router-dom';

// ============================================================================
// 辅助组件
// ============================================================================

/** 懒加载时的占位内容 */
const LoadingFallback: React.FC = () => (
  <div
    style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      height: '100vh',
      fontSize: 18,
      color: '#666',
    }}
  >
    加载中...
  </div>
);

// ============================================================================
// 辅助函数
// ============================================================================

/**
 * 创建“预加载”路由：组件在打包时就加载，页面首次进入时也不会再等待
 */
const createEagerRoute = (
  path: string,
  Component: ComponentType<any>
): RouteObject => ({
  path,
  element: <Component />,
});

/**
 * 创建“懒加载”路由：首次进入时可能会看到短暂的加载提示
 */
const createLazyRoute = (
  path: string,
  loader: () => Promise<{ default: ComponentType<any> }>
): RouteObject => {
  const Component = lazy(loader);
  return {
    path,
    element: (
      <Suspense fallback={<LoadingFallback />}>
        <Component />
      </Suspense>
    ),
  };
};

/** 创建重定向路由 */
const createRedirect = (from: string, to: string): RouteObject => ({
  path: from,
  element: <Navigate to={to} replace />,
});

// ============================================================================
// 预加载的“关键页面”组件（首屏秒开）
// ============================================================================

// 首页和主配置
import Welcome from '../pages/Welcome';
import Main from '../pages/Main';

// NetPyNE 主入口
import NetPyNE from '../components/NetPyNE/NetPyNE';

// 仿真配置 - 通用设置（常用入口）
import SimulationConfigGeneral from '../pages/SimulationConfigGeneral';

// 实验管理（经常访问）
import ExperimentManager from '../pages/ExperimentManager';

// ============================================================================
// 路由配置
// ============================================================================

/**
 * 主要页面路由
 *
 * 说明：
 * - 前半部分：核心页面，使用 createEagerRoute（预加载，首次进入无等待）
 * - 后半部分：其它页面，使用 createLazyRoute（按需加载，减小首屏体积）
 */
const mainRoutes: RouteObject[] = [
  // ---------- 预加载的关键页面（首屏秒开） ----------
  createEagerRoute('/', Welcome),
  createEagerRoute('/cell-config', Main),
  createEagerRoute('/netpyne', NetPyNE),
  createEagerRoute('/simulation-config-general', SimulationConfigGeneral),
  createEagerRoute('/experiment-manager', ExperimentManager),

  // ---------- 懒加载页面（首次进入时可能短暂加载） ----------
  // 模型定义
  createLazyRoute('/populations', () => import('../pages/Populations')),
  createLazyRoute('/syn-mechs', () => import('../pages/SynMechs')),
  createLazyRoute('/conn-rules', () => import('../pages/ConnRules')),
  createLazyRoute('/subcell-conn-rules', () => import('../pages/SubcellConnRules')),
  createLazyRoute('/stim-sources', () => import('../pages/StimSources')),
  createLazyRoute('/stim-targets', () => import('../pages/StimTargets')),

  // 仿真配置（其余）
  createLazyRoute('/simulation-config-record', () => import('../pages/SimulationConfigRecord')),
  createLazyRoute('/simulation-config-network', () => import('../pages/SimulationConfigNetwork')),
  createLazyRoute('/simulation-config-network-v2', () => import('../pages/SimulationConfigNetworkV2')),
  createLazyRoute('/simulation-config-network-editor', () => import('../pages/SimulationConfigNetworkEditor')),
  createLazyRoute('/simulation-config-save', () => import('../pages/SimulationConfigSave')),
  createLazyRoute('/simulation-config-save-v2', () => import('../pages/SimulationConfigSaveV2')),

  // 绘图设置
  createLazyRoute('/plot-settings-raster', () => import('../pages/PlotSettingsRaster')),
  createLazyRoute('/plot-settings-trajectory', () => import('../pages/PlotSettingsTrajectory')),
  createLazyRoute('/plot-settings-lfp', () => import('../pages/PlotSettingsLFP')),

  // 反应扩散
  createLazyRoute('/reaction-diffusion-region', () => import('../pages/ReactionDiffusionRegion')),
  createLazyRoute('/reaction-diffusion-empty', () => import('../pages/ReactionDiffusionEmpty')),

  // 导入功能
  createLazyRoute('/import-neuroml', () => import('../pages/ImportNeuroML')),
  createLazyRoute('/import-python', () => import('../pages/ImportPythonDialog')),

  // 对话框
  createLazyRoute('/select-folder', () => import('../pages/SelectFolderDialog')),
  createLazyRoute('/open-json', () => import('../pages/OpenJSONDialog')),
  createLazyRoute('/save-json', () => import('../pages/SaveJSONDialog')),
  createLazyRoute('/save-json-options', () => import('../pages/SaveJSONDialogOptions')),
  createLazyRoute('/delete-confirm', () => import('../pages/DeleteConfirmDialog')),

  // 特殊页面
  createLazyRoute('/geppetto-test', () => import('../pages/GeppettoTest')),
];

/** 兼容性路由（重定向） */
const legacyRoutes: RouteObject[] = [
  createRedirect('/synaptic-mechanisms', '/syn-mechs'),
  createRedirect('/connectivity-rules', '/conn-rules'),
  createRedirect('/subcellular-connectivity', '/subcell-conn-rules'),
  createRedirect('/stimulation-sources', '/stim-sources'),
  createRedirect('/stimulation-targets', '/stim-targets'),
  createRedirect('/plot-settings-traces', '/plot-settings-trajectory'),
  createRedirect('/reaction-diffusion-extracellular', '/reaction-diffusion-empty'),
];

/** Frame 路由（设计图编号重定向） */
const frameRoutes: RouteObject[] = [
  createRedirect('/frame/8', '/cell-config'),
  createRedirect('/frame/10', '/simulation-config-general'),
  createRedirect('/frame/13', '/plot-settings-raster'),
  createRedirect('/frame/14', '/plot-settings-trajectory'),
  createRedirect('/frame/15', '/reaction-diffusion-region'),
  createRedirect('/frame/16', '/plot-settings-lfp'),
  createRedirect('/frame/17', '/reaction-diffusion-empty'),
  createRedirect('/frame/18', '/simulation-config-record'),
  createRedirect('/frame/19', '/simulation-config-network'),
  createRedirect('/frame/20', '/simulation-config-save'),
  createRedirect('/frame/21', '/simulation-config-network-v2'),
  createRedirect('/frame/22', '/simulation-config-save-v2'),
  createRedirect('/frame/23', '/import-neuroml'),
  createRedirect('/frame/24', '/simulation-config-network-editor'),
  createRedirect('/frame/25', '/experiment-manager'),
  createRedirect('/frame/26', '/select-folder'),
  createRedirect('/frame/27', '/open-json'),
  createRedirect('/frame/28', '/save-json'),
  createRedirect('/frame/29', '/delete-confirm'),
  createRedirect('/frame/30', '/save-json-options'),
  createRedirect('/frame/31', '/import-python'),
];

// ============================================================================
// 导出路由配置
// ============================================================================

/**
 * 应用的完整路由配置（方案 C：核心页面预加载 + 其它页面懒加载）
 */
const routes: RouteObject[] = [
  ...mainRoutes,
  ...legacyRoutes,
  ...frameRoutes,
];

export default routes;

// 可选导出，方便调试或文档使用
export { mainRoutes, legacyRoutes, frameRoutes };

